package com.rongxun.hbwallet.ui.fragment.keystore;


import android.graphics.Bitmap;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.rongxun.base.BaseFragment;
import com.rongxun.hbwallet.R;
import com.rongxun.hbwallet.constants.IntentKey;
import com.rongxun.scancode.qrcode.QRCodeEncode;
import com.rongxun.utils.RxUtil;
import com.rongxun.utils.UUi;
import com.rongxun.widget.LoadingDialog;

import java.io.ByteArrayOutputStream;

import butterknife.BindView;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableOnSubscribe;


/**
 * Created by dwq on 2018/3/27/027.
 * e-mail:lomapa@163.com
 */

public class DeriveKeystoreQRCodeFragment extends BaseFragment {
    @BindView(R.id.iv_keystore)

    ImageView ivKeystore;

    @Override
    public int getLayoutResId() {
        return R.layout.fragment_derive_keystore_qrcode;
    }

    @Override
    protected void init() {

    }

    @Override
    protected void onLazyLoadOnce() {
        super.onLazyLoadOnce();
        LoadingDialog.createTipDialog(activity, R.mipmap.around,
                getString(R.string.derive_keystore_dialog_qrcode_tip1),
                getString(R.string.derive_keystore_dialog_qrcode_tip2), false)
                .show();

        Flowable.create((FlowableOnSubscribe<byte[]>) e -> {

            String walletKeystore = activity.getIntent().getStringExtra(IntentKey.KEYSTORE);

            QRCodeEncode.Builder builder = new QRCodeEncode.Builder();
            builder.setBackgroundColor(0xffffff)
                    .setOutputBitmapHeight(UUi.dip2px(270))
                    .setOutputBitmapWidth(UUi.dip2px(270));
            Bitmap qrCodeBitmap = builder.build().encode(walletKeystore);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            qrCodeBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
            byte[] bytes = baos.toByteArray();
            e.onNext(bytes);
        }, BackpressureStrategy.BUFFER).compose(RxUtil.rxSchedulerHelper()).subscribe(bytes -> Glide.with(activity)
                .load(bytes)
                .into(ivKeystore));
    }
}
